/**
 * Project Reactor
 */


#include "Acceptor.h"

/**
 * Acceptor implementation
 */


/**
 * @param ip
 * @param port
 */
Acceptor::Acceptor(const string & ip, unsigned short port)
:m_addr(ip,port)
{
    // bzero(&m_addr,sizeof(m_addr));
    // m_addr.getInetAddressPtr()->sin_family = AF_INET;
    // m_addr.getInetAddressPtr()->sin_addr.s_addr = inet_addr(ip.c_str());
    // m_addr.getInetAddressPtr()->sin_port = htons(port);
}

Acceptor::~Acceptor() {

}

void Acceptor::ready() {
    m_sock = Socket(socket(AF_INET,SOCK_STREAM,0));
    setReuseAddr();
    setReusePort();
    m_bind();
    m_listen();
}

void Acceptor::setReuseAddr() {
    int opt = 1;
    int ret = setsockopt(m_sock.getFd(),SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
    //todo : ERROR_CHECK(ret);
}

void Acceptor::setReusePort() {
    int opt = 1;
    int ret = setsockopt(m_sock.getFd(),SOL_SOCKET,SO_REUSEPORT,&opt,sizeof(opt));
}

void Acceptor::m_bind() {
    int ret = bind(m_sock.getFd(),(struct sockaddr *)m_addr.getInetAddressPtr(),
    sizeof(struct sockaddr));
    //ERROR_CHECK(ret,-1);
}   

void Acceptor::m_listen() {
    int ret = listen(m_sock.getFd(),128);   
    //ERROR_CHECK(ret,-1);
}

/**
 * @return int
 */
int Acceptor::m_accept() {
    int ret = accept(m_sock.getFd(),NULL,NULL);
    return ret;
}

Socket &Acceptor::getSock(){
    return m_sock;
}